<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" size="small" @click="toggleEdit">
            {{ isEditing ? '保存' : '编辑' }}
          </el-button>
        </div>
      </template>
      
      <el-form 
        ref="profileFormRef" 
        :model="profileForm" 
        :rules="rules"
        label-width="100px"
        :disabled="!isEditing"
      >
        <el-form-item label="用户名">
          <el-input v-model="profileForm.username" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="profileForm.realName"></el-input>
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="profileForm.phone"></el-input>
        </el-form-item>
        
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="profileForm.email"></el-input>
        </el-form-item>
        
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="profileForm.idCard"></el-input>
        </el-form-item>
        
        <el-form-item label="信用评分">
          <el-progress 
            :percentage="profileForm.creditScore" 
            :color="getCreditScoreColor()" 
            :format="formatCreditScore"
          ></el-progress>
        </el-form-item>
      </el-form>
      
      <el-divider>安全设置</el-divider>
      
      <div class="security-options">
        <div class="option-item">
          <span>修改密码</span>
          <el-button type="primary" plain size="small" @click="showChangePasswordDialog">修改</el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" v-model="passwordDialogVisible" width="500px">
      <el-form 
        ref="passwordFormRef" 
        :model="passwordForm" 
        :rules="passwordRules"
        label-width="120px"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password></el-input>
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="changePassword" :loading="passwordChanging">确认修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'
import { getUserInfo, updateUserInfo, changePassword as apiChangePassword } from '@/api/user'

const userStore = useUserStore()
const isEditing = ref(false)
const profileFormRef = ref(null)
const passwordFormRef = ref(null)
const passwordDialogVisible = ref(false)
const passwordChanging = ref(false)

// 表单数据
const profileForm = reactive({
  id: '',
  username: '',
  realName: '',
  phone: '',
  email: '',
  idCard: '',
  creditScore: 100
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ]
}

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const userId = localStorage.getItem('userId')
    if (!userId) {
      ElMessage.warning('用户未登录')
      return
    }
    
    const res = await getUserInfo(userId)
    if (res.code === 200 && res.data) {
      const userData = res.data
      
      // 更新表单数据
      profileForm.id = userData.id
      profileForm.username = userData.username
      profileForm.realName = userData.realName || ''
      profileForm.phone = userData.phone || ''
      profileForm.email = userData.email || ''
      profileForm.idCard = userData.idCard || ''
      profileForm.creditScore = userData.creditScore || 100
      
      // 更新store中的用户信息
      userStore.$patch({ userInfo: userData })
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 切换编辑模式
const toggleEdit = async () => {  
  if (isEditing.value) {
    // 保存编辑
    profileFormRef.value.validate(async (valid) => {
      if (valid) {
        try {
          // Ensure we're sending complete user data with proper password field
          const userData = {...profileForm};
          // Get the stored password from localStorage if available
          const storedUser = JSON.parse(localStorage.getItem('user') || '{}');
          if (storedUser.password) {
            userData.password = storedUser.password;
          }
          
          console.log('正在更新用户资料:', userData);
          const res = await updateUserInfo(userData);
          
          if (res.code === 200 || res.success) {
            ElMessage.success('个人信息更新成功');
            isEditing.value = false;
            // 刷新用户信息
            fetchUserInfo();
            // 更新本地存储的用户信息
            const user = JSON.parse(localStorage.getItem('user') || '{}');
            localStorage.setItem('user', JSON.stringify({...user, ...userData}));
          }
        } catch (error) {
          console.error('更新个人信息失败:', error);
          ElMessage.error('更新个人信息失败: ' + (error.message || '未知错误'));
        }
      }
    });
  } else {
    // 进入编辑模式
    isEditing.value = true;
  }
}

// 显示修改密码对话框
const showChangePasswordDialog = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordDialogVisible.value = true
}

// 修改密码
const changePassword = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordChanging.value = true
      try {
        const res = await apiChangePassword({
          userId: profileForm.id,
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })
        
        if (res.code === 200) {
          ElMessage.success('密码修改成功')
          passwordDialogVisible.value = false
        }
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error(error.response?.data?.message || '修改密码失败')
      } finally {
        passwordChanging.value = false
      }
    }
  })
}

// 信用评分颜色
const getCreditScoreColor = () => {
  const score = profileForm.creditScore
  if (score >= 90) return '#67c23a'  // 优秀 - 绿色
  if (score >= 70) return '#e6a23c'  // 良好 - 黄色
  return '#f56c6c'  // 较差 - 红色
}

// 格式化信用评分显示
const formatCreditScore = (percentage) => {
  return `${percentage}分`
}

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.security-options {
  padding: 10px 0;
}

.option-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}
</style> 